package rita.ui.component;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.HeadlessException;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import rita.settings.HelperEditor;
import rita.settings.Language;
import rita.settings.RobocodeSetting;
import rita.settings.Settings;
import rita.util.RitaUtilities;
import controller.WorkspaceController;
/**
 * Esta clase se encarga de solicitar el nombre del robot. 
 * En caso de necesitar ingresar tambi�n el tipo de robot a crear, deber�a ampliarse 
 * la funcionalidad aqu� (comentado).
 * 
 * @author Vanessa Aybar Rosales
 * */
public class DialogRobotType extends JDialog {
	private ImageIcon[] images;
	private String[] robotStrings = null;
	private JLabel lName = new JLabel(Language.get("robot.name"));
	private JTextField tName = new JTextField("", 20);
	private JTextArea taExplanation = new JTextArea("");
	private JButton bCreate = new JButton(Language.get("ok"));
	private final int WIDTH = 250;
	private final int HEIGHT = 450;
	// private JComboBox comboTypes = null;

	{
		robotStrings = RobocodeSetting.getRobotTypes();
	}

	
	public DialogRobotType(WorkspaceController wc, RMenu menuOrigin) {
		this.setBackground(Color.BLACK);

		this.setTitle(Language.get("robot.new"));
		JPanel namePanel = new JPanel();
		namePanel.setLayout(new FlowLayout());
		lName.setFont(new Font("Ariel", Font.BOLD, 14));
		lName.setForeground(Color.WHITE);
		namePanel.setBackground(Color.BLACK);
		namePanel.add(lName);
		namePanel.add(tName);
		tName.addKeyListener(keyListener);
		tName.setFont(new Font("Ariel", Font.BOLD, 14));
		bCreate.setPreferredSize(new Dimension(140, 40));
		// ImageIcon imgIcon=new
		// ImageIcon(getClass().getResource("support/images/robot/junior.jpg"));
		// //new ImageIcon("support/images/robot/junior.jpg");

		// bCreate.setIcon(new ImageIcon("support/images/robot/junior.jpg"));
		bCreate.setText(Language.get("createRobot"));
		// bCreate.setBackground(Color.getHSBColor(200, 200, 200));
		// bCreate.setForeground(Color.BLACK);
		// bCreate.setFont(new Font("Ariel", Font.BOLD, 14));
		// bCreate.setBorder(BorderFactory
		// .createBevelBorder(javax.swing.border.BevelBorder.RAISED));
		try {
			bCreate.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
		} catch (HeadlessException e1) {
			e1.printStackTrace();
		}
		final WorkspaceController wcTemp = wc;
		// bCreate.addActionListener(new ActionListener() {
		// @Override
		// public void actionPerformed(ActionEvent e) {
		// createRobot(wcTemp);
		// }});
		final RMenu rMenuTemp = menuOrigin;
		bCreate.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				createRobotFromListener(wcTemp, rMenuTemp);
			}

			@Override
			public void mouseEntered(MouseEvent e) {
				e.getComponent().setCursor(
						Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
			}

			@Override
			public void mouseExited(MouseEvent e) {
				e.getComponent().setCursor(Cursor.getDefaultCursor());
			}

		});

		bCreate.addKeyListener(new KeyAdapter() {

			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					createRobotFromListener(wcTemp, rMenuTemp);
				}

			}

		});

		this.add(namePanel, BorderLayout.PAGE_START);

		GridBagConstraints constraints2 = new GridBagConstraints();
		constraints2.gridx = 0; // El �rea de texto empieza en la columna cero.
		constraints2.gridy = 1; // El �rea de texto empieza en la fila cero
		constraints2.gridwidth = 2; // El �rea de texto ocupa dos columnas.
		constraints2.gridheight = 2; // El �rea de texto ocupa 2 filas.

		taExplanation.setBounds(1, 1, 350, 100);
		taExplanation.setLineWrap(true);
		taExplanation.setVisible(false);
		taExplanation.setOpaque(true);
		taExplanation.setEditable(false);
		taExplanation.setWrapStyleWord(true);
		taExplanation.setBackground(Color.RED);
		taExplanation.setForeground(Color.WHITE);
		taExplanation.setFont(new Font("Ariel", Font.BOLD, 12));
		taExplanation.setBorder(BorderFactory.createEtchedBorder());

		// this.add(new JLabel(imgIcon),BorderLayout.WEST);
		JPanel panelButton = new JPanel();
		panelButton.setBackground(Color.BLACK);
		panelButton.add(bCreate);
		this.add(panelButton, BorderLayout.CENTER);
		this.add(taExplanation, BorderLayout.SOUTH);

		this.setModal(true);
		this.setResizable(false);
		this.setSize(this.WIDTH, this.HEIGHT);
		this.pack();
		PositionCalc.centerDialog(this);

		this.setVisible(true);
	}

	private void createRobotFromListener(final WorkspaceController wcTemp,
			final RMenu rMenuTemp) {
		createRobot(wcTemp);
		rMenuTemp.enableSaveWorkspace();
	}

	/*
	 * Este m�todo crea el robot en caso que el nombre del robot no haya sido
	 * ingresado previamente o que el usuario quiera sobreescribirlo (en
	 * realidad lo sobreescribir� cuando haga "Guardar" o
	 * "Compilar y Ejecutar"). Adem�s refresca el workspace con un robot nuevo
	 */
	private void createRobot(WorkspaceController wcTemp) {
		if (tName.getText() == null || tName.getText().trim().length() == 0) {
			taExplanation.setText(Language.get("enterName"));
			taExplanation.setVisible(true);
			return;
		}

		boolean confirm = true;
		if (alreadyExists(tName.getText())) {
			confirm = RitaUtilities.confirmWindow(
					Language.get("confirm.title"), Language.get("confirm.nameAlreadyExists"));
		}
		if (confirm) {
			HelperEditor.currentRobotName = tName.getText();
			WorkspaceController.enableWorkspace(wcTemp,
					HelperEditor.currentRobotType,
					HelperEditor.currentRobotName, null);
			closeDialog();
		}
	}

	/*
	 * Este metodo verifica que el nombre ingresado no exista, y espera
	 * confirmaci�n por el usuario
	 */
	private boolean alreadyExists(String text) {
		final String nameWithoutExt = Settings.getInstallPath()
				+ "robots" + File.separator
				+ Settings.getProperty("defaultpackage") + File.separator
				+ text;
		String fullNameSource = nameWithoutExt + ".java";
		String fullNameClass = nameWithoutExt + ".class";
		File fSource = new File(fullNameSource);
		File fClass = new File(fullNameClass);
		if (fSource.exists() || fClass.exists()) {
			return true;
		}
		return false;
	}

	protected void closeDialog() {
		this.setVisible(false);
		this.dispose();
	}

	/** Returns an ImageIcon, or null if the path was invalid. */
	protected static ImageIcon createImageIcon(String path) {
		java.net.URL imgURL = DialogRobotType.class.getResource(path);
		if (imgURL != null) {
			return new ImageIcon(imgURL);
		} else {
			System.err.println(Language.get("robot.error.fileNotFound") + path);
			return null;
		}
	}

	KeyListener keyListener = new KeyListener() {
		public void keyPressed(KeyEvent keyEvent) {
		}

		/*
		 * S�lo se permite un nombre de clases con letras y n�meros, no los
		 * caracteres de legacy. El primer caracter debe ser una letra y
		 * mayuscula. De no ser as�, por ejemplo si es un n�mero, no se admite.
		 * Si es una letra minuscula, se transforma a una letra mayuscula.
		 */
		public void keyReleased(KeyEvent keyEvent) {
			int keyCode = keyEvent.getKeyCode();

			if (Character.isLetterOrDigit(keyCode)) {
				String dirtyString = tName.getText();
				String cleanString;
				if (dirtyString != null && tName.getText().trim().length() > 0) {
					cleanString = dirtyString.replaceAll("[^a-zA-Z0-9]", "");
					char c = cleanString.charAt(0);
					if (Character.isDigit(c)) {
						if (cleanString.length() > 1)
							cleanString = cleanString.substring(1);
						else
							cleanString = "";
					}
					if (Character.isLowerCase(c)) {
						char upperC = Character.toUpperCase(c);
						cleanString = cleanString.replaceFirst(String
								.valueOf(c), String.valueOf(upperC));
					}

					tName.setText(cleanString);
				}
			}
			taExplanation.setVisible(false);
		}

		public void keyTyped(KeyEvent keyEvent) {
		}

	};
}